﻿using System.Diagnostics;

namespace RuoVea.ExUtil.Machine;

/// <summary>
/// 描 述：系统Shell命令
/// </summary>
public class ExShell
{
    /// <summary>
    /// Bash命令
    /// </summary>
    /// <param name="command">命令</param>
    /// <returns>Bash命令</returns>
    public static string Bash(string command)
    {
        var escapedArgs = command.Replace("\"", "\\\"");
        var process = new Process()
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = $"-c \"{escapedArgs}\"",
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            }
        };
        process.Start();
        string result = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        process.Dispose();
        return result;
    }

    /// <summary>
    /// cmd命令
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="args">参数</param>
    /// <returns>执行结果</returns>
    public static string Cmd(string fileName, string args)
    {
        string output = string.Empty;
        var info = new ProcessStartInfo
        {
            FileName = fileName,
            Arguments = args,
            RedirectStandardOutput = true
        };
        using (var process = Process.Start(info))
        {
            output = process.StandardOutput.ReadToEnd();
        }
        return output;
    }
}
